const express = require('express');

const Results = require('./config/results');

const apiRouter = require('./routes');


const {expressjwt: jwt} = require('express-jwt');
const lock = require('jsonwebtoken')
const options = require('./Handler/system/jwtConfig')
const KEY = require('./config/Key');
const error = require('./Handler/system/error');
const AppConfig = require('./Handler/appConfig')
// 不使用服务器携带cookie也就没有请求头限制问题了
const app = express();


new AppConfig(app)

app.get('/get_session', function (req, res) {
    let a = req.session['a']
    a = lock.verify(a, KEY)
    res.send(a)
})

app.get('/set_session', function (req, res) {
    let token = lock.sign({user: 'admin'}, KEY, {algorithm: "HS256", expiresIn: 60 * 60 * 24})
    req.session['a'] = token
    res.send('已经设置session' + token)
})

app.get('/api/auth', (req, res) => {
    // TODO_05：使用 req.user 获取用户信息，并使用 data 属性将用户信息发送给客户端
    let user = req.auth
    console.log(user)
    res.status(200).cookie('abc', JSON.stringify(user), {
        maxAge: 90,
        httpOnly: true,
        sameSite: "none",
        secure: false
    }).json(Results.success(200, "ok", {
        cookie: req.cookies,
        tips: '使用的是token,没用到cookie',
        'exp-iat': user.exp - user.iat,
        'username': user.username,
    }))
})

app.use('/api', jwt(options.jwtOptions).unless(options.unlessObject), apiRouter)


//关于错误处理

app.use(error)

app.listen(2698, () => {
    console.log('Express server running at http://127.0.0.1:2698')
});
